import { message } from "antd";
import Const from "./const";

/**
 * 判断对象是否为空
 * @param {Object} obj 
 * @returns Boolean
 */
const isEmpty = (obj) => {
  return JSON.stringify(obj) === "{}";
};

/**
 * 快速POST并保存返回结果
 * @param {*} url 请求地址
 * @param {*} params 请求参数
 * @param {*} commonChange 该页面的commonChange
 * @param {*} saveName 要存到store里的字段名
 * @param {*} successMsg 成功提示
 */
const simplePost = async (url, params, commonChange, saveName, successMsg) => {
  const res = await Fetch(url, {
    method: "POST",
    body: JSON.stringify(params),
  });
  if (res.code === Const.successCode) {
    commonChange(saveName, res.context);
    if (successMsg) {
      message.success(successMsg);
    }
  } else {
    message.error(res.message);
  }
};

/**
 * 快速get并保存结果
 * @param {*} url 
 * @param {*} commonChange 
 * @param {*} saveName 
 */
const simpleGet = async (url, commonChange, saveName) => {
  const res = await Fetch(url);
  commonChange(saveName, res.context);
};

/**
 * 获取路由参数，传入需要返回的参数名，返回参数值
 * @param {*} variable 参数名
 * @returns
 */
export function getUrlParam(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return false;
}

/**
 * 获取路由参数，传入页面url，返回所有参数
 * @param {*} url
 * @returns
 */
export function queryURLParams(url) {
  let pattern = /(\w+)=(\w+)/gi; //定义正则表达式

  let parames = {}; // 定义参数对象

  url.replace(pattern, ($, $1, $2) => {
    parames[$1] = $2;
  });

  return parames;
}

const Fetch = async (url, query) => {
  let result;
  await fetch(url, query)
    .then((res) => res.json())
    .then((res) => {
      result = res;
    });
  return result;
};

export { Fetch, simplePost, simpleGet, isEmpty };
